package com.education.ai;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.List;

/**
 * 应用程序入口类
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        logger.debug("Running with Spring Boot v2.7.0, Spring v5.3.20");
        SpringApplication.run(Application.class, args);
    }

    /**
     * 数据库表结构检查组件
     */
    @Component
    static class DatabaseStructureChecker {
        
        private static final Logger logger = LoggerFactory.getLogger(DatabaseStructureChecker.class);
        
        @PersistenceContext
        private EntityManager entityManager;
        
        @EventListener
        @Transactional(readOnly = true)
        public void onApplicationEvent(ContextRefreshedEvent event) {
            logger.info("检查数据库表结构...");
            
            try {
                // 检查teachers表结构
                checkTeachersTable();
                
                logger.info("数据库表结构检查完成");
            } catch (Exception e) {
                logger.error("数据库表结构检查失败: {}", e.getMessage(), e);
            }
        }
        
        /**
         * 检查教师表结构
         */
        private void checkTeachersTable() {
            try {
                // 检查teachers表的列信息
                Query query = entityManager.createNativeQuery(
                        "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'teachers'");
                List<String> columns = query.getResultList();
                
                // 检查是否存在password列
                if (!columns.contains("password")) {
                    logger.warn("教师表缺少password列，尝试添加...");
                    try {
                        entityManager.createNativeQuery(
                                "ALTER TABLE teachers ADD COLUMN password VARCHAR(255) NOT NULL DEFAULT 'temp_password' COMMENT '密码'")
                                .executeUpdate();
                        logger.info("已添加password列");
                    } catch (Exception e) {
                        logger.error("添加password列失败: {}", e.getMessage());
                    }
                }
                
                // 检查是否存在salt列
                if (!columns.contains("salt")) {
                    logger.warn("教师表缺少salt列，尝试添加...");
                    try {
                        entityManager.createNativeQuery(
                                "ALTER TABLE teachers ADD COLUMN salt VARCHAR(100) NULL COMMENT '密码盐'")
                                .executeUpdate();
                        logger.info("已添加salt列");
                    } catch (Exception e) {
                        logger.error("添加salt列失败: {}", e.getMessage());
                    }
                }
                
                // 检查是否存在phone列
                if (!columns.contains("phone")) {
                    logger.warn("教师表缺少phone列，尝试添加...");
                    try {
                        entityManager.createNativeQuery(
                                "ALTER TABLE teachers ADD COLUMN phone VARCHAR(20) NULL COMMENT '手机号'")
                                .executeUpdate();
                        logger.info("已添加phone列");
                    } catch (Exception e) {
                        logger.error("添加phone列失败: {}", e.getMessage());
                    }
                }
                
                // 检查是否存在email列
                if (!columns.contains("email")) {
                    logger.warn("教师表缺少email列，尝试添加...");
                    try {
                        entityManager.createNativeQuery(
                                "ALTER TABLE teachers ADD COLUMN email VARCHAR(100) NULL COMMENT '邮箱'")
                                .executeUpdate();
                        logger.info("已添加email列");
                    } catch (Exception e) {
                        logger.error("添加email列失败: {}", e.getMessage());
                    }
                }
                
                // 检查是否存在status列
                if (!columns.contains("status")) {
                    logger.warn("教师表缺少status列，尝试添加...");
                    try {
                        entityManager.createNativeQuery(
                                "ALTER TABLE teachers ADD COLUMN status INT(1) DEFAULT 1 COMMENT '状态：1-启用，0-禁用'")
                                .executeUpdate();
                        logger.info("已添加status列");
                    } catch (Exception e) {
                        logger.error("添加status列失败: {}", e.getMessage());
                    }
                }
                
                // 检查是否存在last_login_time列
                if (!columns.contains("last_login_time")) {
                    logger.warn("教师表缺少last_login_time列，尝试添加...");
                    try {
                        entityManager.createNativeQuery(
                                "ALTER TABLE teachers ADD COLUMN last_login_time DATETIME NULL COMMENT '最后登录时间'")
                                .executeUpdate();
                        logger.info("已添加last_login_time列");
                    } catch (Exception e) {
                        logger.error("添加last_login_time列失败: {}", e.getMessage());
                    }
                }
            } catch (Exception e) {
                logger.error("检查teachers表结构失败: {}", e.getMessage(), e);
            }
        }
    }
} 